package com.hcc.security.handler;

import com.hcc.security.enetity.User;
import com.hcc.security.mapper.UserMapper;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

/**
 * 自定义登录成功处理器
 *
 * @version 1.0
 * @author: Administrator
 * @date: 2019/4/28
 */
@Component
@Slf4j
public class MyAuthenctiationSuccessHandler implements AuthenticationSuccessHandler {

  @Autowired
  private UserMapper userMapper;


  @Value("${default_target_url}")
  private String defaultTargetUrl;

  @Override
  public void onAuthenticationSuccess(HttpServletRequest request,
      HttpServletResponse response, Authentication authentication)
      throws IOException, ServletException {
    this.saveLoginInfo(request, authentication);
    log.info("登录成功,即将forward:" + this.defaultTargetUrl);
    // 登录成功之后将SECURITY放入上下文中
    request.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
    request.getRequestDispatcher(this.defaultTargetUrl).forward(request, response);
  }

  private void saveLoginInfo(HttpServletRequest request, Authentication authentication) {
    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    user.setLastLoginTime(user.getLoginTime());
    user.setLoginTime(new Date());
    user.setLoginCount(user.getLoginCount()+1);
    log.info("登录用户:" + user.getLoginName());
    user.setLoginCount(user.getLoginCount()+1);
    user.setLastLoginTime(user.getLoginTime() != null ? user.getLoginTime() : new Date());
    user.setLoginTime(new Date());
    this.userMapper.updateLoginInfo(user);
  }

}
